package com.atguigu.lease.web.admin.controller.apartment;


import com.atguigu.lease.common.result.Result;
import com.atguigu.lease.model.entity.AttrKey;
import com.atguigu.lease.model.entity.AttrValue;
import com.atguigu.lease.web.admin.service.AttrKeyService;
import com.atguigu.lease.web.admin.service.AttrValueService;
import com.atguigu.lease.web.admin.vo.attr.AttrKeyVo;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;


@Tag(name = "房间属性管理")
@RestController
@RequestMapping("/admin/attr")
public class AttrController {

    @Autowired
    private AttrKeyService attrKeyService;

    @Autowired
    private AttrValueService attrValueService;

    @Operation(summary = "新增或更新属性名称")
    @PostMapping("key/saveOrUpdate")
    public Result saveOrUpdateAttrKey(@RequestBody AttrKey attrKey) {
        return attrKeyService.saveOrUpdate(attrKey) ? Result.ok() : Result.fail();
    }

    @Operation(summary = "新增或更新属性值")
    @PostMapping("value/saveOrUpdate")
    public Result saveOrUpdateAttrValue(@RequestBody AttrValue attrValue) {
        return attrValueService.saveOrUpdate(attrValue) ? Result.ok() : Result.fail();
    }


    /**
     * 看接口文档  返回值类型没有实体类对应  -> VO 出现了  和前端视图属性一样
     * 创建一个VO   AttrVo extends AttrKey + List<AttrValue>
     * 本次是多表查询  attr_key 和 attr_value 的外连接查询  需要自定义sql语句  ->  关注 逻辑字段删除字段！！！  is_deleted = 0
     * 外连接中  on后面放子表的条件  否则可能会变成内连接null导致的
     */
    @Operation(summary = "查询全部属性名称和属性值列表")
    @GetMapping("list")
    public Result<List<AttrKeyVo>> listAttrInfo() {
        List<AttrKeyVo> attrKeyVoList = attrKeyService.customList();
        return Result.ok(attrKeyVoList);
    }

    /**
     * 删除主表数据 attr_key 需要删除对应的子表数据 attr_value 否则会产生孤儿数据（垃圾数据）
     *
     * @param attrKeyId
     * @return
     */
    @Operation(summary = "根据id删除属性名称")
    @DeleteMapping("key/deleteById")
    public Result removeAttrKeyById(@RequestParam Long attrKeyId) {
        // 删除主表数据
        boolean remove = attrKeyService.removeById(attrKeyId);
        if (remove) {
            // 删除子表数据
            LambdaQueryWrapper<AttrValue> attrValueLambdaQueryWrapper = new LambdaQueryWrapper<>();
            attrValueLambdaQueryWrapper.eq(AttrValue::getAttrKeyId, attrKeyId);
            attrValueService.remove(attrValueLambdaQueryWrapper);
            return Result.ok();
        }
        return Result.fail();
    }

    @Operation(summary = "根据id删除属性值")
    @DeleteMapping("value/deleteById")
    public Result removeAttrValueById(@RequestParam Long id) {
        attrValueService.removeById(id);
        return Result.ok();
    }

}
